<template>
  <div class="measure-container">
    <div ref="argisMap" class="map-container"></div>
    
    <!-- 工具栏 -->
    <div class="toolbar">
      <button @click="startMeasure('distance')" :class="{ active: measureType === 'distance' }">
        测距
      </button>
      <button @click="startMeasure('area')" :class="{ active: measureType === 'area' }">
        测面
      </button>
      <button @click="clearMeasurements">
        清除
      </button>
    </div>
  </div>
</template>

<script>
import { coordinates } from '@/utils/geometry'

export default {
  name: 'MeasureTool',
  
  data() {
    return {
      map: null,
      view: null,
      measureType: null,
      draw: null,
      graphicsLayer: null,
      measurement: null,
      measureTooltip: null,
      Graphic: null
    }
  },

  mounted() {
    this.$nextTick(() => {
      this.initMap()
    })
  },

  methods: {
    initMap() {
      // 确保 require 存在
      if (!window.require) {
        console.error('ArcGIS API not loaded')
        return
      }

      window.require([
        'esri/Map',
        'esri/views/MapView',
        'esri/layers/GraphicsLayer',
        'esri/widgets/Sketch',
        'esri/geometry/geometryEngine',
        'esri/Graphic',
        'esri/layers/WebTileLayer'
      ], (Map, MapView, GraphicsLayer, Sketch, geometryEngine, Graphic, WebTileLayer) => {
        // 保存 Graphic 类的引用
        this.Graphic = Graphic;
        
        // 创建地图
        this.map = new Map({
          basemap: "topo"
        })

        // 添加天地图底图
        let webTileLayer = new WebTileLayer({
          id: '天地图影像',
          visible: true,
          urlTemplate: `https://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&transparent=true&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&tk=8c88eba266a165eac9c085724708f2f9`
        })
        this.map.add(webTileLayer)

        // 创建视图
        this.view = new MapView({
          container: this.$refs.argisMap,
          map: this.map,
          zoom: 6,
          center: [85, 42.2], 
        })

        // 创建图形图层
        this.graphicsLayer = new GraphicsLayer()
        this.map.add(this.graphicsLayer)

        // 初始化绘图工具
        this.sketch = new Sketch({
          view: this.view,
          layer: this.graphicsLayer,
          availableCreateTools: ['polyline', 'polygon'],
          creationMode: 'single',
          defaultCreateOptions: {
            mode: 'click' // 点击模式
          },
        })

        // 设置线和面的默认样式
        this.sketch.viewModel.polygonSymbol = {
          type: "simple-fill",
          color: [64, 158, 255, 0.2],
          outline: {
            color: [64, 158, 255, 0.8],
            width: 2
          }
        }
        
        this.sketch.viewModel.polylineSymbol = {
          type: "simple-line",
          color: [64, 158, 255, 0.8],
          width: 3,
          style: "solid"
        }

        // 监听绘制事件
        this.sketch.on('create', (event) => {
          if (event.state === 'complete') {
            const geometry = event.graphic.geometry
            
            if (this.measureType === 'distance') {
              const length = geometryEngine.geodesicLength(geometry, 'kilometers')
              this.showMeasurement(geometry, `${length.toFixed(3)} 公里`)
            } else if (this.measureType === 'area') {
              const area = geometryEngine.geodesicArea(geometry, 'square-kilometers')
              this.showMeasurement(geometry, `${area.toFixed(3)} 平方公里`)
            }
          }
        })

        // 移除默认的缩放控件
        this.view.ui.remove('zoom')
        // 移除 attribution
        this.view.ui.remove('attribution')
      })
    },

    startMeasure(type) {
      if (this.measureType === type) {
        this.stopMeasure()
        return
      }

      this.measureType = type
      
      if (type === 'distance') {
        this.sketch.create('polyline')
      } else if (type === 'area') {
        this.sketch.create('polygon')
      }
    },

    stopMeasure() {
      this.measureType = null
      if (this.sketch) {
        this.sketch.cancel()
      }
    },

    showMeasurement(geometry, text) {
      // 创建标注
      const labelGraphic = new this.Graphic({
        geometry: geometry.centroid || geometry,
        symbol: {
          type: 'text',
          color: 'white',
          haloColor: 'black',
          haloSize: 1,
          text: text,
          font: {
            size: 12,
            weight: 'bold'
          }
        }
      })

      this.graphicsLayer.add(labelGraphic)
    },

    clearMeasurements() {
      if (this.graphicsLayer) {
        this.graphicsLayer.removeAll()
      }
      this.stopMeasure()
    }
  },

  beforeDestroy() {
    if (this.view) {
      this.view.destroy()
    }
  }
}
</script>

<style scoped>
.measure-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.map-container {
  width: 100%;
  height: 100%;
}

.toolbar {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: white;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  z-index: 1000;
  display: flex;
  gap: 10px;
}

.toolbar button {
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s;
}

.toolbar button:hover {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
}

.toolbar button.active {
  color: #fff;
  background-color: #409eff;
  border-color: #409eff;
}

/* 测量结果样式 */
:deep(.esri-sketch__button) {
  display: none;
}

:deep(.measurement-label) {
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}
</style> 